package rpcserver

import (
	"net"
	"net/http"
	"net/rpc"

	"smartconn.cc/cubestruct/Msg"
	"smartconn.cc/cubestruct/Service/rpchandle/rpcclient"
	"smartconn.cc/tosone/logstash"
)

var listen net.Listener

// Service :an object export from service to app
type Service int

// StartConn define
func StartConn() {
	logstash.Info("Init rpc server for service-end ...")
	//server := rpc.NewServer()
	service := new(Service)
	rpc.Register(service)
	rpc.HandleHTTP()
	var err error
	for {
		listen, err = net.Listen("unix", "/tmp/nbc_service.rpc")
		if err != nil {
			logstash.Error(err.Error())
		} else {
			logstash.Info("Init rpc server for service-end successfully ...")
			break
		}
	}

	//server.Accept(l)
	go http.Serve(listen, nil)
}

// StopConn define
func StopConn() {
	logstash.Info("Stop rpc server for service-end ...")
	listen.Close()
}

// ConnectToAPPServer define
func (t *Service) ConnectToAPPServer(status *Msg.APPServerStatus, reply *bool) error {
	if status.Done {
		*reply = rpcclient.StartConn()
	}
	appServerReady <- true
	return nil
}

// DisconnectFromAPPServer define
func (t *Service) DisconnectFromAPPServer(status *Msg.APPServerStatus, reply *bool) error {
	if !status.Done {
		*reply = rpcclient.StopConn()
	}
	return nil
}

var appServerReady chan bool

// WaitForConnectToAPPServer define
func WaitForConnectToAPPServer() {
	select {
	case <-appServerReady:
		return
	}
}

func init() {
	appServerReady = make(chan bool, 1)
}
